﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using WeiboSDK;

namespace Cnblogs
{
    public partial class LoginWeiboPage : PhoneApplicationPage
    {
        private bool _isClearBackStack = false;
        public LoginWeiboPage()
        {
            InitializeComponent();
            loadLoginControl();
        }

        private void loadLoginControl()
        {
            LoginControl control = new LoginControl();
            control.SetKeyInfo(Constants.GetAppKey(), Constants.GetAppKeySecret());
            control.action += (p) =>
            {
                App.Token = p;
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    if (string.IsNullOrEmpty(App.Status) && NavigationService.CanGoBack)
                    {
                        NavigationService.GoBack();
                    }
                    else
                    {
                        _isClearBackStack = true;
                        NavigationService.Navigate(new Uri(Constants.P_SendWeiboPage, UriKind.Relative));
                    }  
                });                 
            };
            this.LayoutRoot.Children.Add(control);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (_isClearBackStack)
            {
                if (NavigationService.CanGoBack)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        NavigationService.RemoveBackEntry();
                    });
                }
            }
            base.OnNavigatedFrom(e);
        }
    }
}